"""
    Author:
    Date: 2019-01-17

    公会管理后台

    该系统的用户使用手机号码注册和登录.
"""

import json

from entities import guild_mgr
from entities import photo_mgr
from entities import sms_mgr
from entities import user_mgr
from entities import video_mgr
from entities.err import *

from . import helpers
from utils.log import Log


def index(request):
    """ 首页 """
    context = helpers.build_context(request)

    # 如果用户没有登录，则进入登录界面
    mobile = helpers.get_request_mobile(request)
    if mobile is None:
        context['template'] = 'guild/login.html'
        return ERROR_NO_ERROR, context

    # 用户不存在, 也进入登录界面
    guild = guild_mgr.get_guild_by_mobile(mobile)
    if guild is None:
        return ERROR_INVALID_GUILD_ID

    context['guild'] = guild
    context['total_members_count'] = len(guild_mgr.get_guild_members(guild['id']))
    context['template'] = 'guild/home.html'
    return ERROR_NO_ERROR, context


def login(request, mobile, sms_code):
    """ 用户登录 """
    mobile = mobile.strip()
    if not mobile:
        return ERROR_INVALID_MOBILE

    sms_code = sms_code.strip()
    if not sms_code:
        return ERROR_INVALID_SMS_CODE

    # 检测验证码是否合法
    if not sms_mgr.is_valid_sms_code(mobile, sms_code):
        return ERROR_INVALID_SMS_CODE

    guild = guild_mgr.get_guild_by_mobile(mobile)
    if guild is None:
        return ERROR_INVALID_GUILD_MOBILE

    # 保存登录状态
    helpers.login(request, mobile)
    return ERROR_NO_ERROR


def user_list(request, begin_time, end_time):
    """ 获取指定时间范围内的统计数据 """
    mobile = helpers.get_request_mobile(request)
    if not mobile:
        return ERROR_NOT_LOGIN, None

    guild = guild_mgr.get_guild_by_mobile(mobile)
    if guild is None:
        return ERROR_SYSTEM_ERROR, None

    context = helpers.build_context(request)
    context['template'] = 'guild/user_stat.html'
    context['guild'] = guild
    context['users'] = guild_mgr.get_guild_members_stat_data(guild['id'], begin_time, end_time)
    return ERROR_NO_ERROR, context


def daily_stat(request, days):
    """ 每日统计 """
    mobile = helpers.get_request_mobile(request)
    if not mobile:
        return ERROR_NOT_LOGIN, None

    guild = guild_mgr.get_guild_by_mobile(mobile)
    if guild is None:
        return ERROR_SYSTEM_ERROR, None

    context = helpers.build_context(request)
    context['template'] = 'guild/stat.html'
    context['guild'] = guild
    context['stat_data'] = guild_mgr.get_guild_daily_stat_data(guild['id'], days)
    return ERROR_NO_ERROR, context


def weekly_stat(request, weeks):
    """ 每周统计 """
    mobile = helpers.get_request_mobile(request)
    if not mobile:
        return ERROR_NOT_LOGIN, None

    guild = guild_mgr.get_guild_by_mobile(mobile)
    if guild is None:
        return ERROR_SYSTEM_ERROR, None

    context = helpers.build_context(request)
    context['template'] = 'guild/stat.html'
    context['guild'] = guild
    context['stat_data'] = guild_mgr.get_guild_weekly_stat_data(guild['id'], weeks)
    return ERROR_NO_ERROR, context


def monthly_stat(request, months):
    """ 每月统计 """
    mobile = helpers.get_request_mobile(request)
    if not mobile:
        return ERROR_NOT_LOGIN, None

    guild = guild_mgr.get_guild_by_mobile(mobile)
    if guild is None:
        return ERROR_SYSTEM_ERROR, None

    context = helpers.build_context(request)
    context['template'] = 'guild/stat.html'
    context['guild'] = guild
    context['stat_data'] = guild_mgr.get_guild_monthly_stat_data(guild['id'], months)
    return ERROR_NO_ERROR, context


def members(request):
    """ 获取指定时间范围内的统计数据 """
    mobile = helpers.get_request_mobile(request)
    if not mobile:
        return ERROR_NOT_LOGIN, None

    guild = guild_mgr.get_guild_by_mobile(mobile)
    if guild is None:
        return ERROR_SYSTEM_ERROR, None

    context = helpers.build_context(request)
    context['template'] = 'guild/member_list.html'
    context['guild'] = guild
    context['members'] = guild_mgr.get_guild_members(guild['id'])
    return ERROR_NO_ERROR, context


def caster_detail(request, uid):
    """ 主播详情 """
    # 判断用户是否存在
    user = user_mgr.get_broadcaster_detail(uid)
    if user is None:
        return ERROR_USER_NOT_EXIST, None

    mobile = helpers.get_request_mobile(request)
    if not mobile:
        return ERROR_NOT_LOGIN, None

    guild = guild_mgr.get_guild_by_mobile(mobile)
    if guild is None:
        return ERROR_SYSTEM_ERROR, None

    # 判断用户是否属于自己的公会
    guild_id = guild['id']
    if guild_id != guild_mgr.get_user_guild_id(uid):
        return ERROR_PERMISSION_DENIED, None

    # 提取用户的视频列表
    videos = video_mgr.get_user_video_list(uid)
    sample_videos = []
    if videos:
        sample_videos = videos[:2] if videos else []

    # 提取用户的相册
    sample_images = []
    if 'images' in user:
        sample_images = user['images'][:2] if user['images'] else []

    context = helpers.build_context(request)
    context['template'] = 'guild/caster_detail.html'

    context['is_banned'] = user_mgr.is_banned_user(uid)
    context['total_call_seconds'] = user_mgr.get_broadcaster_total_call_seconds(uid)
    context['liveid'] = user_mgr.get_active_liveid(uid)

    context['user'] = user
    context['is_busy'] = 'checked="checked"' if user['is_busy'] else ''
    context['is_ios_device'] = 'iphone' in user['last_login_phone'].lower()
    context['sample_images'] = sample_images
    context['auth_photo'] = photo_mgr.get_user_authing_photo_by(uid)
    context['waiting_auth_video_count'] = video_mgr.get_user_waiting_auth_video_count(uid)
    context['sample_videos'] = sample_videos

    context['total_online_seconds'] = user_mgr.get_broadcaster_total_online_seconds(uid)
    context['total_income'] = user_mgr.get_broadcaster_total_income(uid)
    context['total_video_count'] = video_mgr.get_user_video_count(uid)
    return ERROR_NO_ERROR, context


def caster_video_list(request, uid):
    """ 获取用户的视频列表 """
    user = user_mgr.get_broadcaster_detail(uid)
    context = helpers.build_context(request)
    context['template'] = 'guild/caster_video_list.html'
    context['user'] = user
    context['videos'] = video_mgr.get_user_video_list(uid)
    return ERROR_NO_ERROR, context


def caster_album(request, uid):
    """ 个人相册 """
    user = user_mgr.get_broadcaster_detail(uid)

    auth_images = []
    photo = photo_mgr.get_user_authing_photo_by(uid)
    if photo is not None:
        try:
            auth_images = json.loads(photo['images_json'])
        except Exception as e:
            Log.error(f'照片格式解析失败: uid={uid}')

    context = helpers.build_context(request)
    context['template'] = 'guild/caster_album.html'
    context['user'] = user
    context['auth_images'] = auth_images
    context['photo'] = photo
    return ERROR_NO_ERROR, context


def view_video(request, vid):
    """ 视频的查看页面 """
    video = video_mgr.get_video_info(vid)
    context = helpers.build_context(request)
    context['template'] = 'guild/view_video.html'
    context['video_url'] = video['video_url']
    context['video_id'] = vid
    return ERROR_NO_ERROR, context


def gallery(request, image):
    """ 头像的查看页面 """
    context = helpers.build_context(request)
    context['template'] = 'guild/gallery.html'
    context['image_url'] = image
    return ERROR_NO_ERROR, context


if __name__ == '__main__':
    print('ok')
